package com.dqp.cslggroup.JWXT;

import android.annotation.SuppressLint;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewStub;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import androidx.appcompat.widget.Toolbar;
import androidx.preference.PreferenceManager;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.dqp.cslggroup.Api.jwxtApi;
import com.dqp.cslggroup.Api.xxmhApi;
import com.dqp.cslggroup.EventBus.MessageEvent;
import com.dqp.cslggroup.Features.Setting;
import com.dqp.cslggroup.R;
import com.dqp.cslggroup.UI.AlertDialog;
import com.dqp.cslggroup.UI.BaseActivity;
import com.dqp.cslggroup.UI.ExamAdapter;
import com.dqp.cslggroup.UI.MyApplication;
import com.dqp.cslggroup.Util.*;
import com.dqp.cslggroup.bean.exam;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


public class SearchExam extends BaseActivity {
    private Spinner cx_spinner_year, cx_spinner_term;
    private Button cx_button;
    private int cx_year, cx_term;
    private String cx_year_str, cx_term_str;
    private Map<String, String> cx_exam_cookies;
    private String stuNum, use_url;
    private ListView listView;
    private Boolean show_c = true;
    private ViewStub viewstub_loading;
    ExecutorService threadPool = Executors.newFixedThreadPool(2);

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_inquire);
        EventBus.getDefault().register(this);
        Toolbar toolbar = findViewById(R.id.include_toolbar);
        toolbar.setTitle("");
        setSupportActionBar(toolbar);
        Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
        stuNum = SharedPreferencesUtil.getStringSp(this, "stuNum", null);
        getCookies();
        initCmp();
        cx_Grade();
    }

    public void getCookies() {
        Map<String, String> map = SharedPreferencesUtil.getMap(this, "cookies");
        long time = SharedPreferencesUtil.getLongSp(this, "cookiesTime", 0);
        long nowTime = GetTimeUtil.getCurrentTimeMillis();
        long x = GetTimeUtil.minuteDifference(nowTime, time);
        if (x < 10) {
            cx_exam_cookies = map;
        } else {
            String xxmh = SharedPreferencesUtil.getStringSp(this, "password_XXMH", null);
            String sno = SharedPreferencesUtil.getStringSp(this, "stuNum", null);
            String jwxt = SharedPreferencesUtil.getStringSp(this, "password_JWXT", null);
            if (!StringUtil.isEmpty(xxmh, sno, jwxt)) {
                viewstub_loading.setVisibility(View.VISIBLE);
                threadPool.execute(() -> {
                    JSONObject jsonObject = xxmhApi.login(sno, xxmh, "0");
                    if (Result.jsonResultIsTure(jsonObject)) {
                        JSONObject object = jsonObject.getJSONObject("info");
                        Map<String, String> xxmhCookies = JSONObject.parseObject(object.toJSONString(), new TypeReference<Map<String, String>>() {
                        });
                        if (xxmhCookies == null || xxmhCookies.size() < 2) return;
                        object = jwxtApi.login(xxmhCookies, sno, jwxt, "0");
                        if (Result.jsonResultIsTure(object)) {
                            cx_exam_cookies = xxmhCookies;
                            CookiesUtil.save(this, cx_exam_cookies);
                        }
                    } else if (jsonObject.containsKey("resultMsg") && jsonObject.getJSONObject("resultMsg").containsKey("密码错误")) {
                        alertDialog("密码错误", "您绑定的信息门户账号密码错误，您近期是否进行了密码更改？" +
                                "现已无法正常使用该模块功能，为确保正常使用请前往设置重新绑定！");
                    }
                });
            } else {
                alertDialog("账号未绑定", "检测到您绑定的信息门户、教务系统账号或密码信息缺失，无法正常使用该模块功能，" +
                        "为确保正常使用请前往设置进行绑定！");
            }
        }
    }

    public void alertDialog(String title, String msg) {
        AlertDialog alertDialog = new AlertDialog(this);
        alertDialog.builder();
        alertDialog.setGone()
                .setTitle(title)
                .setMsg(msg)
                .setMsgGravity(false)
                .setNegativeButton("设置", R.color.colorAccent, v1 -> {
                    alertDialog.dismiss();
                    UiUtils.startActivity(this, Setting.class);
                })
                .setPositiveButton("取消", R.color.colorAccent, v2 -> {
                    alertDialog.dismiss();
                    finish();
                })
                .show();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void initCmp() {
        cx_spinner_term = findViewById(R.id.cx_spinner_term);
        cx_spinner_year = findViewById(R.id.cx_spinner_year);
        cx_button = findViewById(R.id.cx_button);
        listView = findViewById(R.id.cx_list);
        viewstub_loading = findViewById(R.id.viewstub_loading);
        TextView title = findViewById(R.id.cxcj_title);
        TextView ksmc = findViewById(R.id.text_xf);
        TextView kssj = findViewById(R.id.text_cj);
        TextView cdmc = findViewById(R.id.text_jd);
        TextView kcmc = findViewById(R.id.text_kc);
        kcmc.setText("课程名称");
        title.setText("考场查询");
        ksmc.setText("考试名称");
        cdmc.setText("考试地点");
        kssj.setText("考试时间");
        int month = GetTimeUtil.getMonth();
        int year = GetTimeUtil.getYear();
        if (month < 8 && month >= 2) {
            cx_spinner_year.setSelection(year - 2017);
            cx_spinner_term.setSelection(1);
        } else {
            if (month > 7) year++;
            cx_spinner_year.setSelection(year - 2017);
            cx_spinner_term.setSelection(0);
        }

    }

    @SuppressLint("HandlerLeak")
    private void cx_Grade() {
        cx_button.setOnClickListener(view -> {
            listView.setAdapter(null);
            EventBus.getDefault().post(new MessageEvent("SearchExam", 2, null));
            new Thread(() -> {
                try {
                    cx_year_str = cx_spinner_year.getSelectedItem().toString();
                    cx_term_str = cx_spinner_term.getSelectedItem().toString();
                    int[] arr_year = StringUtil.SelectNumber(cx_year_str);
                    cx_year = arr_year[0];
                    int[] arr_term = StringUtil.SelectNumber(cx_term_str);
                    cx_term = arr_term[0];
                    JSONObject jsonObject = jwxtApi.getExam(stuNum, cx_year + "", cx_term + "", cx_exam_cookies);
                    if (Result.jsonResultIsTure(jsonObject)) {
                        List<exam> examList = new ArrayList<>();
                        if (jsonObject.containsKey("details")) {
                            jsonObject = jsonObject.getJSONObject("details");
                            if (jsonObject.containsKey("exam")) {
                                JSONArray gradeTable = jsonObject.getJSONArray("exam");
                                for (Object o : gradeTable) {
                                    JSONObject lesson = (JSONObject) o;
                                    exam exam = new exam();
                                    exam.setCdmc(lesson.getString("cdmc"));
                                    exam.setKcmc(lesson.getString("kcmc"));
                                    exam.setKsmc(lesson.getString("ksmc"));
                                    exam.setKssj(lesson.getString("kssj"));
                                    examList.add(exam);
                                }
                                EventBus.getDefault().post(new MessageEvent("SearchExam", 1, examList));
                            }
                        }

                    }
                } catch (Exception e) {
                    EventBus.getDefault().post(new MessageEvent("SearchExam", 4, null));
                    e.printStackTrace();
                }

            }).start();
        });
    }


    private void initList(List<exam> dataList) {
        if (dataList == null || dataList.size() == 0) {
            ToastUtil.showToast("该时段未安排考场信息！");
        } else {
            ExamAdapter examAdapter = new ExamAdapter(dataList, this);
            listView.setAdapter(examAdapter);
            showDialog(dataList);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        if (event.getEvent().equals("SearchExam")) {
            switch (event.getWhat()) {
                case 1:
                    viewstub_loading.setVisibility(View.GONE);
                    List<exam> examList = (List<exam>) event.getObj();
                    initList(examList);
                    break;
                case 2:
                    viewstub_loading.setVisibility(View.VISIBLE);
                    break;

                case 4:
                    viewstub_loading.setVisibility(View.GONE);
                    ToastUtil.showToast("🤦网络异常");

                    break;
                case 5:
                    viewstub_loading.setVisibility(View.GONE);
                    ToastUtil.showToast("🤦未查询到相关数据");
                    break;
            }
        }
    }

    public void showDialog(List<com.dqp.cslggroup.bean.exam> dataList) {
        SharedPreferences sp;
        SharedPreferences.Editor editor;
        boolean show;
        sp = PreferenceManager.getDefaultSharedPreferences(SearchExam.this);
        editor = sp.edit();
        show = sp.getBoolean("show_kao", false);
        editor.apply();
        Date d = new Date();
        @SuppressLint("SimpleDateFormat") DateFormat df = new SimpleDateFormat("yyyy");
        String Dates = df.format(d);
        if (!show && cx_spinner_year.getSelectedItem().toString().contains(Dates) && show_c) {
            final com.dqp.cslggroup.UI.AlertDialog alertDialog = new com.dqp.cslggroup.UI.AlertDialog(SearchExam.this);
            alertDialog.builder();
            alertDialog.setGone()
                    .setTitle("考试周模式")
                    .setMsg("是否将考试安排添加到应用主界面？")
                    .setNegativeButton("添加", R.color.colorAccent, v -> {
                                SharedPreferences sp1;
                                SharedPreferences.Editor editor1;
                                sp1 = PreferenceManager.getDefaultSharedPreferences(SearchExam.this);
                                editor1 = sp1.edit();
                                editor1.putBoolean("show_kao", true);
                                editor1.apply();
                                for (com.dqp.cslggroup.bean.exam exam : dataList)
                                    MyApplication.getDaoInstant().getExamDao().insertOrReplace(exam);
                                EventBus.getDefault().post(new MessageEvent("MainActivity", 4, null));
                                ToastUtil.showToast("考场安排将会显示在主界面！");

                            }
                    )
                    .setPositiveButton("取消", R.color.colorAccent, null)
                    .show();
        }
        show_c = false;
    }

}
